/***************************************************************************
 * Copyright 2012-2013 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the contract ICT-257367.
 *
 * Authors:
 *      Cristoforo Seccia
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.schema.osgi;

import it.txt.access.capability.factory.CapabilitySchemaFactory;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactory;

import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ManagedService;


/**
 *
 * @author Cristoforo Seccia
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
 */
public class Activator implements BundleActivator {

    private static final Logger LOGGER = Logger.getLogger(Activator.class.getName());
    private static ClassLoader contextClassLoader;
    private static final int MANAGED_SERVICE_REGISTRATION_COUNT = 2;
    private ServiceRegistration<?>[] managedServiceRegs;
    private ENSAuthorisationRequestFactoryMS requestFactoryService;
    private ENSAuthorisationResponseFactoryMS responseFactoryService;
    public static final String CAPABILITY_SCHEMAS_DIRECTORY_PROP_KEY = "capability.schema.dir";
    
    public void start(BundleContext context) throws Exception {
        long id = context.getBundle().getBundleId();
        LOGGER.log(Level.INFO, "[ENS Schemas]: Bundle ID: {0}", id);
        setContextClassLoader(Activator.class.getClassLoader());
        
        managedServiceRegs = new ServiceRegistration<?>[MANAGED_SERVICE_REGISTRATION_COUNT];
        
        Dictionary<String,String> properties = new Hashtable<String,String>();
        properties.put(Constants.SERVICE_PID, RegisteredServices.ENS_AUTHZ_REQUEST_FACTORY_MS_PID);
        requestFactoryService = new ENSAuthorisationRequestFactoryMS(context);
        int i = 0;
        managedServiceRegs[i++] = context.registerService(
            ManagedService.class, requestFactoryService, properties);
        
        responseFactoryService = new ENSAuthorisationResponseFactoryMS(context);
        properties = new Hashtable<String,String>();
        properties.put(Constants.SERVICE_PID, RegisteredServices.ENS_AUTHZ_RESPONSE_FACTORY_MS_PID);
        managedServiceRegs[i] = context.registerService(ManagedService.class, responseFactoryService, properties);
        
        //added because the capability verifier need an instance of CapabilitySchemaFactory
        CapabilitySchemaFactory.getInstance(context.getProperty(CAPABILITY_SCHEMAS_DIRECTORY_PROP_KEY));
        
        //Request and Response factories
        Hashtable<String,Object> factoriesProperties = new Hashtable<String, Object>(1);
        factoriesProperties.put(ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY,
            context.getProperty(ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY));
        //this activator is in charge of configuring the singleton instance of the request factory
        ServiceReference<ConfigurationAdmin> configAdminSR =
                context.getServiceReference(ConfigurationAdmin.class);
        ConfigurationAdmin configAdmin = context.getService(configAdminSR);
        try {
            Configuration requestConfig = configAdmin.getConfiguration(
                it.txt.ens.schema.osgi.RegisteredServices.ENS_AUTHZ_REQUEST_FACTORY_MS_PID, null);
            requestConfig.update(factoriesProperties);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        factoriesProperties = new Hashtable<String, Object>(1);
        factoriesProperties.put(ENSAuthorisationResponseFactory.SCHEMAS_DIRECTORY_PROP_KEY,
            context.getProperty(ENSAuthorisationResponseFactory.SCHEMAS_DIRECTORY_PROP_KEY));
        try {
            //configure the singleton instance of the response factory
            Configuration responseConfig = configAdmin.getConfiguration(
                it.txt.ens.schema.osgi.RegisteredServices.ENS_AUTHZ_RESPONSE_FACTORY_MS_PID, null);
            responseConfig.update(factoriesProperties);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void stop(BundleContext context) throws Exception {
        for (ServiceRegistration<?> reg : managedServiceRegs)
            reg.unregister();
        requestFactoryService.unregister();
        responseFactoryService.unregister();
    }

    public static ClassLoader getContextClassLoader() {
        return contextClassLoader;
    }

    public static void setContextClassLoader(ClassLoader contextClassLoader) {
        Activator.contextClassLoader = contextClassLoader;
    }
}
